﻿using Autofac;
using Ewell.BizComponent.Service.IServer;
using Ewell.BizComponent.Service.Model.Request;
using Ewell.BizComponent.Service.Model.Response;
using Ewell.BizComponent.Service.Server;
using Ewell.BizComponent.UI.Core.Model;
using Ewell.BizComponent.UI.Core.VievModel;
using Ewell.BizComponent.UI.SearchPersonCom.Model;
using Ewell.Interface.Common.Model.Common;
using Ewell.Interface.Common.Model.GateWay.Dto.Basic;
using Ewell.Interface.Common.Model.GateWay.Dto.InsuranceManager;
using Ewell.Interface.Common.Model.GateWay.GateWayUriInfo;
using Ewell.Interface.Common.Utils;
using MahApps.Metro.Controls.Dialogs;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace Ewell.BizComponent.UI.SearchPersonCom.ViewModel
{
    public class SearchPersonComVm : ViewModelBase
    {
        /// <summary>
        /// 检索按钮
        /// </summary>
        private List<SearchPersonComBtnVm> _searchPersonComBtnList;
        public List<SearchPersonComBtnVm> searchPersonComBtnList
        {
            get { return _searchPersonComBtnList; }
            set
            {
                if (_searchPersonComBtnList != value)
                {
                    _searchPersonComBtnList = value;
                    OnPropertyChanged(nameof(searchPersonComBtnList));
                }
            }
        }
        /// <summary>
        /// 检索文本框
        /// </summary>
        private string _searchText;
        public string searchText
        {
            get
            {
                return _searchText;
            }
            set
            {
                if (value != _searchText)
                {
                    _searchText = value;
                    OnPropertyChanged(nameof(searchText));
                }
            }
        }
        /// <summary>
        /// 检索框Mark
        /// </summary>
        private string _searchTextMark;
        public string searchTextMark
        {
            get
            {
                return _searchTextMark;
            }
            set
            {
                if (value != _searchTextMark)
                {
                    _searchTextMark = value;
                    OnPropertyChanged(nameof(searchTextMark));
                }
            }
        }
        /// <summary>
        /// 业务代码
        /// </summary>
        public string currBizTradeCode { get; set; }
        /// <summary>
        /// 医保患者信息
        /// </summary>
        private MedInsurPatientVm _medInsurPatientVm;
        public MedInsurPatientVm medInsurPatientVm
        {
            get=> _medInsurPatientVm;
            set
            {
                if(value != _medInsurPatientVm)
                {
                    _medInsurPatientVm = value;
                    OnPropertyChanged(nameof(medInsurPatientVm));
                }
            }
        }
        /// <summary>
        /// 医保患者扩展信息
        /// </summary>
        private MedPatientExtVm _medPatientExtVm;
        public MedPatientExtVm medPatientExtVm
        {
            get => _medPatientExtVm;
            set
            {
                if( value != _medPatientExtVm)
                {
                    _medPatientExtVm = value;
                    OnPropertyChanged(nameof(medPatientExtVm));
                }
            }
        }
        /// <summary>
        /// 读卡结果
        /// </summary>
        public ReadCardResponse readCardResponse { get; set; }
        /// <summary>
        /// 患者检索结果
        /// </summary>
        private List<PatientVm> _patientVmResponse;
        public List<PatientVm> patientVmResponse
        {
            get => _patientVmResponse;
            set
            {
                if (_patientVmResponse != value)
                {
                    _patientVmResponse = value;
                    OnPropertyChanged(nameof(patientVmResponse));
                }
            }
        }

        public IReadCardServer readCardServer { get; set; } = Global.Container.Resolve<IReadCardServer>();
        public IDialogCoordinator dialogCoordinator { get; set; } = DialogCoordinator.Instance;
        /// <summary>
        /// 扩展信息源格式
        /// </summary>
        public MedPatientExt medPatientExt { get; set; }
        /// <summary>
        /// 读卡完成事件
        /// </summary>
        public event Action<SearchPersonComVm> SearchFinashHandle;

        public ICommand readCardCmd => new RelayCommand(async param =>
        {
            var buttonComponent = param as SearchPersonComBtnVm;
            if (buttonComponent == null) return;
            if (buttonComponent.interfaceId.HasValue && buttonComponent.interfaceId.Value != 0)
            {
                try
                {
                    this.readCardResponse = this.readCardServer.readCard(new ReadCardRequest()
                    {
                        searchTypeCoding = buttonComponent.bizSearchTypeCoding,
                        searchValue = searchText,
                        currBizTradeCode = currBizTradeCode,
                        interfaceId = buttonComponent.interfaceId.ToString(),
                        uuheader = JsonConvert.SerializeObject(LoginInfo.loginUser),
                    });
                }
                catch (SpeedException ex)
                {
                    Application.Current.Dispatcher.BeginInvoke(async () =>
                    {
                        await dialogCoordinator.ShowMessageAsync(this, "错误!", "读卡失败!" + ex.Message);
                    });
                    return;
                }
                catch (Exception ex)
                {
                    Application.Current.Dispatcher.BeginInvoke(async () =>
                    {
                        await dialogCoordinator.ShowMessageAsync(this, "错误!", "读卡失败!" + ex.Message);
                    });
                    return;
                }
            }

            IndexSearchReq indexSearchReq = new IndexSearchReq()
            {
                searchTypeCoding = buttonComponent.bizSearchTypeCoding,
                searchValue = searchText,
                cardNo = this.readCardResponse?.cardNo,
                cardType = this.readCardResponse?.cardType,
            };
            BizSearchDubboService bizSearchDubboService = new BizSearchDubboService();
            var gateWayResult = bizSearchDubboService.queryMemberByExample.Post<IndexSearchResultResp<QueryMemberByExampleResp>>(indexSearchReq);
            if (!gateWayResult.success)
            {
                Application.Current.Dispatcher.BeginInvoke(async () =>
                {
                    await dialogCoordinator.ShowMessageAsync(this, "错误!", "检索患者失败!" + gateWayResult.message);
                });
                return;
            }
            List<PatientVm> patientVms = new List<PatientVm>();
            if (gateWayResult.@object.data.list != null)
            {
                foreach (var item in gateWayResult.@object.data.list)
                {
                    var patient=item.CopyProperties<PatientVm>();
                    patient.patientTypeDesc = item.patientTypeName;
                    patientVms.Add(patient);
                }
            }
            this.patientVmResponse = patientVms;
            if (this.readCardResponse!=null)
            {
                GetInsurInfo(readCardResponse);
            }
            SearchFinashHandle?.Invoke(this);
        });

        private void GetInsurInfo(ReadCardResponse readCardResponse)
        {
            QueryMedInsurPatientReq queryMedInsurPatientReq = new QueryMedInsurPatientReq()
            {
                idCardNo = this.readCardResponse.cardNo,
                idCardTypeCoding = this.readCardResponse.cardType,
            };
            MedInsurPatientDubboService medInsurPatientDubboService = new MedInsurPatientDubboService();
            var gateWay = medInsurPatientDubboService.queryMedInsurPatientByExample.Post<List<MedInsurPatientVm>>(queryMedInsurPatientReq);
            if (!gateWay.success) return;
            this.medInsurPatientVm = gateWay.@object.FirstOrDefault();

            this.medPatientExt = JsonConvert.DeserializeObject<MedPatientExt>(this.medInsurPatientVm.extInfo);
            MedPatientExtVm medPatientExtVm = new MedPatientExtVm()
            {
                medPatientExtCommVmList = new List<MedPatientExtCommVm>(),
                extList=new List<MedPatientExtListVm>(),
            };
            foreach (var item in medPatientExt.data.Properties())
            {
                if (item.Value.Type == JTokenType.Array)
                {
                    foreach (var token in item.Value<JToken>())
                    {
                        medPatientExtVm.extList.Add(new MedPatientExtListVm()
                        {
                            data=token?.ToList<object>(),
                            title= medPatientExt.titleAndAttribute.FirstOrDefault(f=>f.dataIndex== item.Path).title,
                        });
                    }
                }
                else
                {
                    var attri = medPatientExt.titleAndAttribute.FirstOrDefault(f => f.dataIndex == item.Path);
                    medPatientExtVm.medPatientExtCommVmList.Add(new MedPatientExtCommVm()
                    {
                        name= item.Path,
                        value= item.Value.ToString(),
                        display= attri.display,
                        title=attri.title,
                    });
                }
            }
            this.medPatientExtVm = medPatientExtVm;
        }
    }
}
